package com.gexin.controller.commom;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSONArray;
import com.gexin.common.VerificationCodeTool;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.utils.IdGenerateUtils;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
/**
 * 生成校验图片
 * @author 
 *
 */
@ControllerBind(controllerKey = "/api/ver/getVerImg", viewPath = "jsp/demo/")
public class VerificationImgController extends Controller {
	private static Log log = Log.getLog(VerificationImgController.class);

	@SuppressWarnings("unused")
	public void index() {
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
		try {
			// set encoding
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// Verification code tool
			VerificationCodeTool vcTool = new VerificationCodeTool();
			BufferedImage image = vcTool.drawVerificationCodeImage();
			String imageString = null;
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try {
				ImageIO.write(image, "JPEG", bos);
				byte[] imageBytes = bos.toByteArray();
				Base64 encoder = new Base64();
				imageString = encoder.encodeAsString(imageBytes);
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			int vcResult = vcTool.getXyresult();
			String vcValue = vcTool.getRandomString();
			// 结果保存在session
			String token = IdGenerateUtils.getId("L");
			// getSession().setAttribute(token,vcResult);
			CacheUtils.set(token, vcResult, 300);// 有效时间5分钟
			// System.out.println("获取验证码成功 :\n验证码:"+vcValue+"\n验证码结果:"+vcResult);
			Random r = new Random();
			int num1 = r.nextInt(10) - 5;// -5到5之间的随机数
			int num2 = r.nextInt(10) - 5;//
			while (num1 == 0) {
				num1 = r.nextInt(10) - 5;
			}
			while (num2 == 0) {
				num2 = r.nextInt(10) - 5;
			}
			int a = vcResult + num1, b = vcResult + num2, c = vcResult;
			int[] result = new int[] { a, b, c };
			// 冒泡排序
			for (int i = 0; i < result.length; i++) {
				for (int j = i; j < result.length; j++) {
					if (result[i] > result[j]) {
						int x = result[i];
						result[i] = result[j];
						result[j] = x;
					}
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("img", "data:image/jpeg;base64," + imageString);
			map.put("token", token);
			map.put("result", JSONArray.toJSON(result));
			renderJson(new AjaxCmd(map));
		} catch (Exception e) {
			log.info("获取验证码失败");
		}
	}

	public void verify() {
		// String result = getSession().getAttribute(getPara("token")).toString();
		String result = CacheUtils.get(getPara("token")).toString();
		if (result == null) {
			renderJson(new AjaxCmd(false, "验证码已失效"));
			return;
		}
		if (getPara("code").equals(result)) {
			renderJson(new AjaxCmd(true, "验证通过"));
		} else {
			renderJson(new AjaxCmd(false, "验证码不正确"));
		}
	}

}
